package com.snailvr.tv.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.pwittchen.networkevents.library.ConnectivityStatus;
import com.github.pwittchen.networkevents.library.event.ConnectivityChanged;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.snail.gift.GiftClient;
import com.snail.gift.GiftClientCaller;
import com.snail.media.player.ISnailPlayer;
import com.snail.media.player.ISnailPlayer.EventType;
import com.snail.media.player.ISnailPlayer.ISnailPlayerErrorNotification;
import com.snail.media.player.ISnailPlayer.ISnailPlayerEventNotification;
import com.snail.media.player.ISnailPlayer.ISnailPlayerStateChangeNotification;
import com.snail.readyvr.R;
import com.snail.readyvr.activity.PersonalCenterActivity;
import com.snail.readyvr.application.MyApplication;
import com.snail.readyvr.di.module.ApplicationModule;
import com.snail.readyvr.event.GetSessionEvent;
import com.snail.readyvr.event.LoginEvent;
import com.snail.readyvr.mvp.model.UnityInitParam;
import com.snail.readyvr.rest.GetSessionUtils;
import com.snail.readyvr.util.Constant;
import com.snail.readyvr.util.DefaultBusWrapper;
import com.snail.readyvr.util.IntentParams;
import com.snail.readyvr.util.LogUtils;
import com.snail.readyvr.util.SPUtils;
import com.snail.readyvr.util.StartActivityUtils;
import com.snail.readyvr.util.ToastUtils;
import com.snail.readyvr.util.Utils;
import com.snailvr.tv.Definition;
import com.snailvr.tv.contract.ChannelContact;
import com.snailvr.tv.event.ChannelChangeEvent;
import com.snailvr.tv.event.GifEvent;
import com.snailvr.tv.event.MessageEvent;
import com.snailvr.tv.event.RoomChangeEvent;
import com.snailvr.tv.network.entity.ChannelInfoResponBean;
import com.snailvr.tv.network.entity.ChannelListResponBean;
import com.snailvr.tv.network.entity.PlayUrlResponBean;
import com.snailvr.tv.network.entity.RoomInfoBean;
import com.snailvr.tv.presenter.ChannelPresenter;
import com.snailvr.tv.ui.adapter.MessageAdapter;
import com.snailvr.tv.ui.base.CheckPermissionsActivity;
import com.snailvr.tv.ui.data.DefEmoticons;
import com.snailvr.tv.ui.data.DefGifticons;
import com.snailvr.tv.ui.data.GiftMessage;
import com.snailvr.tv.ui.data.SnailMessage;
import com.snailvr.tv.ui.view.EmotionKeyboard;
import com.snailvr.tv.ui.view.SnailPlayerVideoView;
import com.snailvr.tv.util.StringUtils;

import org.json.JSONException;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import party.loveit.iflytek.core.SpeechResult;
import party.loveit.iflytek.interfaces.SpeechResultListener;
import pl.droidsonroids.gif.GifImageView;

import static com.snail.readyvr.util.Utils.token;
import static com.snailvr.tv.Definition.CHANNEL_ID_NAME;
import static com.snailvr.tv.Definition.KEY_FOV;
import static com.snailvr.tv.Definition.KEY_SNVR_EYE_MODE;
import static com.snailvr.tv.Definition.KEY_SNVR_NAVIGATION;
import static com.snailvr.tv.Definition.PLAY_SETTING_RESULT_CODE;
import static com.snailvr.tv.Definition.SNVR_PROJ_DOME;
import static com.snailvr.tv.Definition.SNVR_PROJ_PLANE;
import static com.snailvr.tv.Definition.SNVR_PROJ_SPHERE;
import static com.snailvr.tv.Definition.SNVR_VIDEO_SPLICE_FMT_2D;
import static com.snailvr.tv.Definition.SNVR_VIDEO_SPLICE_FMT_3D_OVU;
import static com.snailvr.tv.Definition.SNVR_VIDEO_SPLICE_FMT_3D_SBS;
import static com.snailvr.tv.Definition.TYPE_180_2D;
import static com.snailvr.tv.Definition.TYPE_180_3D_Left_Right;
import static com.snailvr.tv.Definition.TYPE_180_3D_Up_Down;
import static com.snailvr.tv.Definition.TYPE_2D;
import static com.snailvr.tv.Definition.TYPE_360_2D;
import static com.snailvr.tv.Definition.TYPE_360_3D_Left_Right;
import static com.snailvr.tv.Definition.TYPE_360_3D_Up_Down;


public class PlayActivity extends CheckPermissionsActivity implements ChannelContact.IChanelView, GiftClientCaller, SpeechResultListener {

    @BindView(R.id.layout_root_view)
    FrameLayout mLayoutRootView;

    @BindView(R.id.video_view)
    SnailPlayerVideoView mVideoView;

    @BindView(R.id.controller_view)
    RelativeLayout mControllerView;

    @BindView(R.id.layout_controller_top)
    RelativeLayout mLayoutControllerTop;
    @BindView(R.id.img_view_channel_logo)
    ImageView mImgViewChannelLogo;

    @BindView(R.id.txt_view_channel_name)
    TextView mTxtViewChannelName;

    @BindView(R.id.txt_view_room_name)
    TextView mTextViewRoomName;

    @BindView(R.id.button_me)
    Button mButtonMe;

    @BindView(R.id.layout_controller_bottom)
    RelativeLayout mLayoutControllerBottom;
    @BindView(R.id.layout_controller_right)
    RelativeLayout mLayoutControllerRight;

    @BindView(R.id.txt_view_time)
    TextView mTxtViewTime;
    @BindView(R.id.txt_view_current_time)
    TextView mTxtViewCurrentTime;
    @BindView(R.id.img_view_preview)
    ImageView mImgViewPreview;
    @BindView(R.id.img_view_pause)
    ImageView mImgViewPause;
    @BindView(R.id.img_view_next)
    ImageView mImgViewNext;
    @BindView(R.id.button_switch)
    Button mButtonSwitch;
    @BindView(R.id.button_room_list)
    Button mButtonRoomList;
    @BindView(R.id.layout_button_room_list)
    RelativeLayout mRelativeLayoutRoomList;
    @BindView(R.id.button_reset)
    Button mButtonReset;


    @BindView(R.id.buffering_view)
    RelativeLayout mBufferingView;

    @BindView(R.id.img_view_play)
    ImageView mPlayView;

    @BindView(R.id.txt_view_channel_online_num)
    TextView mChannelOnLineNum;

    @BindView(R.id.txt_video_name)
    TextView mTextViewVideoName;

    @BindView(R.id.img_no_network)
    ImageView mImgNoNetWork;

    @BindView(R.id.txt_view_buffering)
    TextView mTextViewBuffering;

    @BindView(R.id.emotion_keyboard)
    EmotionKeyboard mEmotionKeyboard;

    @BindView(R.id.text_view_message_button)
    TextView mTextViewMessageButton;
    @BindView(R.id.button_message)
    Button mButtonMessage;
    @BindView(R.id.layout_button_message)
    RelativeLayout mRelativeLayoutMessage;

    @BindView(R.id.id_layout_message_view)
    RelativeLayout mLayoutMessageView;
    @BindView(R.id.recycler_view_message_box)
    RecyclerView mRecyclerViewMessageBox;

    @BindView(R.id.gif_img_view)
    GifImageView mGifImageView;

    @BindView(R.id.edit_text_keyboard)
    EditText mEditText;

    private GiftClient mClient;

    private List<SnailMessage> mMessageList;
    private MessageAdapter mMessageAdapter;

    //TO DO check is_logined

    public final static int REQUEST_UNITY_CODE = 100;
    public final static int RESULT_UNITY_CODE = 100 + 1;
    private final String mUrl = "http://live.hkstv.hk.lxdns.com/live/hks/playlist.m3u8";
    private String mPlayUrl = "";
    private GestureDetector mGestureDetector = null;
    private static final int GESTURE_TYPE_NO = 0;
    private static final int GESTURE_TYPE_HRO = 1;
    private static final int GESTURE_TYPE_VER = 2;
    private int cur_gesture_type;

    private int mDuration;

    private int mFov;
    private int mNavigationMode;
    private int mEyesMode;
    private int mProjectionMode;
    private int mDome_H;
    private int mDome_V;

    private static final String SWITCH_TYPE_UP = "up";
    private static final String SWITCH_TYPE_DOWN = "down";


    public static RoomInfoBean mRoomInfoBean;

    private ChannelInfoResponBean.DataBean mCurChannelBean;
    private InputMethodManager mInputMethodManager;

    /**
     * 当前频道号
     * 当前房间号
     */
    private int mIntChannelId = 0;
    private int mIntRoomId = 0;
    /**
     * 当前频道序列号
     */
    public static int channel_index = 0;

    private static final int SHOW_TIME = 1;
    private static final int HIDE_NAV = 2;
    private static final int MESSAGE_CLIENT_LOGIN = 3;
    private static final int RECEIVE_NEW_MESSAGE = 4;
    private static final int RECEIVE_NEW_GIFT_MESSAGE = 5;
    private static final int HIDE_GIF_VIEW = 6;
    private static final int RELOGIN_GIFT_SERVER = 7;
    private static final int SHOW_NET_SPEED = 8;



    private int mCurrentTime = -1;

    private boolean mIsOffLine = false;

    // 首次进入默认取第一个频道信息
    private int page_size = 10;
    private int page = 0;
    private boolean from_url = false;

    private String regEx_180_2D = "^.*_180(\\.\\w*)?$";
    private String regEx_180_TB = "^.*_180_TB(\\.\\w*)?$";
    private String regEx_180_LR = "^.*_180_LR(\\.\\w*)?$";
    private String regEx_360_2D = "^.*_360(\\.\\w*)?$";
    private String regEx_360_TB = "^.*_360_TB(\\.\\w*)?$";
    private String regEx_360_LR = "^.*_360_LR(\\.\\w*)?$";

    private boolean mIsMessageKeyBoardShow = false;
    private boolean mIsMessageDialogShow = true;


    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB
    }

    TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            showNetSpeed();
        }
    };

    private void showNetSpeed() {
        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        if ( nowTimeStamp != lastTimeStamp) {
            long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

            lastTimeStamp = nowTimeStamp;
            lastTotalRxBytes = nowTotalRxBytes;

            Message msg = mHandler.obtainMessage();
            msg.what = SHOW_NET_SPEED;
            msg.obj = String.valueOf(speed) + " kb/s";

            mHandler.sendMessage(msg);//更新界面
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == SHOW_TIME) {
                if (mCurrentTime >= 0) {
                    mCurrentTime ++;
                    mTxtViewCurrentTime.setText(generateTime(mCurrentTime));
                    msg = obtainMessage(SHOW_TIME);
                    sendMessageDelayed(msg,1000);
                }
            } else if (msg.what == HIDE_NAV) {
                if (mLayoutControllerBottom.getVisibility() == View.VISIBLE) {
                    mLayoutControllerTop.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_top_out));
                    mLayoutControllerTop.setVisibility(View.GONE);
                    mLayoutControllerBottom.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
                    mLayoutControllerBottom.setVisibility(View.GONE);
                    mLayoutControllerRight.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.out_from_right));
                    mLayoutControllerRight.setVisibility(View.GONE);

                }
            } else if (msg.what == MESSAGE_CLIENT_LOGIN) {
                mButtonMessage.setEnabled(true);
                mRelativeLayoutMessage.setEnabled(true);
            }  else if (msg.what == RECEIVE_NEW_MESSAGE) {
                mMessageAdapter.notifyDataSetChanged();
                mRecyclerViewMessageBox.smoothScrollToPosition(mMessageList.size());
            } else if (msg.what == RECEIVE_NEW_GIFT_MESSAGE) {
                GiftMessage _GiftMessage = (GiftMessage) msg.obj;
                mGifImageView.setImageResource(DefGifticons.giftHashMap.get(_GiftMessage.getMessage()));
                mGifImageView.setVisibility(View.VISIBLE);
                sendEmptyMessageDelayed(HIDE_GIF_VIEW,2000);
            } else if (msg.what == HIDE_GIF_VIEW) {
                mGifImageView.setVisibility(View.GONE);
            } else if (msg.what == RELOGIN_GIFT_SERVER) {
                if(mClient!=null) {
                    mClient.login(ApplicationModule.DANMU_HOST,ApplicationModule.DANMU_HOST_PORT,String.valueOf(mIntRoomId), Utils.token);
                }
            } else if (msg.what == SHOW_NET_SPEED) {
                mTextViewBuffering.setText(getResources().getString(R.string.buffer_hint) + "..." + msg.obj);
            }
        }
    };


    @OnClick({R.id.img_view_channel_list,R.id.layout_channel_list})
    public void showChannelListDialog() {
        toggleMediaControlsVisiblity();
        Intent intent = new Intent(this, ChannelListActivity.class);
        intent.putExtra(CHANNEL_ID_NAME, mIntChannelId);
        this.startActivity(intent);
    }

    @OnClick({R.id.button_room_list,R.id.layout_button_room_list})
    public void showRoomListActivity() {
        toggleMediaControlsVisiblity();
        Intent intent = new Intent(this, RoomsActivity.class);
        intent.putExtra(CHANNEL_ID_NAME,mIntChannelId);
        this.startActivity(intent);
    }

    @OnClick({R.id.button_reset,R.id.layout_button_reset})
    public void resetAngleofVideo() {
        mHandler.removeMessages(HIDE_NAV);
        mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
        if(mVideoView!=null) {
            mVideoView.setOriginalAngle();
        }
    }



//    @OnClick({R.id.button_setting,R.id.layout_button_setting})
//    public void showSettingActivity() {
//        toggleMediaControlsVisiblity();
//        Intent intent = new Intent(this, SettingActivity.class);
//        this.startActivityForResult(intent,PLAY_SETTING_RESULT_CODE);
//    }
//
//    @OnClick(R.id.button_share)
//    public void showShareActivity() {
//        toggleMediaControlsVisiblity();
//        Intent intent = new Intent(this, ShareActivity.class);
//        this.startActivity(intent);
//    }

    @OnClick({R.id.button_switch,R.id.layout_button_switch})
    public void switchEyeMode() {
        mHandler.removeMessages(HIDE_NAV);
        mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
       if(mCurChannelBean == null || mRoomInfoBean == null){
            ToastUtils.show(this, R.string.no_ready_tip);
            return;
        }

        mVideoView.stopPlayback();
        /*if (mEyesMode == Definition.SNVR_SINGLE_EYES_MODE) {
            mEyesMode = Definition.SNVR_DOUBLE_EYES_MODE;
        } else if (mEyesMode == Definition.SNVR_DOUBLE_EYES_MODE) {
            mEyesMode = Definition.SNVR_SINGLE_EYES_MODE;
        }
        setEyesMode(mEyesMode);*/
       // startActivity(new Intent("com.snail.readyvr.activity.UnityPlayerActivity", Uri.parse("readyvr://ready.vr.cm")));

         UnityInitParam unityInitParam = new UnityInitParam() ;
         unityInitParam.setHost(ApplicationModule.HOST);
         unityInitParam.setProjectStyle(mProjectionMode + "");
         unityInitParam.setToken(token);
         unityInitParam.setSessionid(Utils.sessionid);
         unityInitParam.setViewAngle(mFov + "");
        unityInitParam.setLang(Utils.getUnityLang(this));
        if(from_url){
            unityInitParam.setUrl(mPlayUrl);
            //unityInitParam.setChannelid("0");
        }else {
            unityInitParam.setUrl(null);
            //unityInitParam.setChannelid(String.valueOf(mIntChannelId));
        }
        mCurChannelBean.setDefault_room_info(mRoomInfoBean);
        unityInitParam.setChannel(JSON.toJSONString(mCurChannelBean));
        unityInitParam.setDebug(1);
        unityInitParam.setRole("guest");
        if(Utils.sUser != null && !StringUtils.isBlank(Utils.sUser.getToken()))
            unityInitParam.setRole("user");
         //Intent intent = new Intent(this, UnityPlayerActivity.class);
         //intent.putExtra(IntentParams.UNITY_PARAM, JSON.toJSONString(unityInitParam));
       // mVideoView.stopPlayback();
        // finish();
        LogUtils.d(JSON.toJSONString(unityInitParam));
        Intent intent = new Intent("com.snail.readyvr.activity.UnityPlayerActivity", Uri.parse("readyvr://snail.com"));
        if(Utils.myAccountInfo != null) {
            unityInitParam.setRole(Utils.myAccountInfo.getRole());
            intent.putExtra(IntentParams.UNITY_ACCOUNT_PARAM, Utils.myAccountInfo);
        }
        intent.putExtra(IntentParams.UNITY_PARAM, JSON.toJSONString(unityInitParam));
        /*intent.putExtra(IntentParams.UNITY_PARAM, "{" +
                "  \"debug\" : 0," +
                "  \"sessionid\" : \"148663144770\"," +
                "  \"viewAngle\" : \"80\"," +
                "  \"channel\" : \"{\\\"charge\\\":false,\\\"icon\\\":\\\"http:\\\\\\/\\\\\\/epg.readyvr.woniucloud.com\\\\\\/mz\\\\\\/cache\\\\\\/snailTV\\\\\\/pagefile\\\\\\/b54a2cbbca38c793e01c63febcef6da7.jpg\\\",\\\"id\\\":25,\\\"default_room_info\\\":{\\\"id\\\":69,\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/epg.readyvr.woniucloud.com\\\\\\/mz\\\\\\/cache\\\\\\/snailTV\\\\\\/pagefile\\\\\\/b54a2cbbca38c793e01c63febcef6da7.jpg\\\",\\\"living\\\":false,\\\"eye_style\\\":0,\\\"u3d_bg\\\":\\\"http:\\\\\\/\\\\\\/epg.readyvr.woniucloud.com\\\\\\/mz\\\\\\/cache\\\\\\/snailTV\\\\\\/pagefile\\\\\\/b54a2cbbca38c793e01c63febcef6da7.jpg\\\",\\\"view_angle\\\":90,\\\"charge\\\":false,\\\"desc\\\":\\\"蜗牛VR日本之行180度3D，直播；CDN分发\\\",\\\"tag\\\":\\\"\\\",\\\"control_model\\\":0,\\\"playurl\\\":\\\"http:\\\\\\/\\\\\\/live.feicui.flv.woniucloud.com\\\\\\/live\\\\\\/zyf2.flv\\\",\\\"project_style\\\":3,\\\"online\\\":100,\\\"name\\\":\\\"游日本 180度3D\\\"},\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/epg.readyvr.woniucloud.com\\\\\\/mz\\\\\\/cache\\\\\\/snailTV\\\\\\/pagefile\\\\\\/b54a2cbbca38c793e01c63febcef6da7.jpg\\\",\\\"desc\\\":\\\"大千世界\\\",\\\"name\\\":\\\"大千世界\\\"}\"," +
                "  \"role\" : \"user\"," +
                "  \"host\" : \"http:\\/\\/epg.readyvr.woniucloud.com\\/\"," +
                "  \"token\" : \"7f66a88c7f2ad9e9ec5a6dacdd55317d\"," +
                "  \"projectStyle\" : \"3\"" +
                "}");*/

        if(mCurChannelBean.getDefault_room_info() != null){
            intent.putExtra(IntentParams.UNITY_ROOMID_PARAM, mCurChannelBean.getDefault_room_info().getId() + "");
        }
        intent.putExtra(IntentParams.UNITY_TOKEN_PARAM, token);
        startActivityForResult(intent,REQUEST_UNITY_CODE);
        LogUtils.d("end");
    }

    @OnClick(R.id.img_view_play)
    public void startToPlay() {
        mHandler.removeMessages(HIDE_NAV);
        mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
        if(mVideoView.getVideoStatus() == ISnailPlayer.State.PLAYER_PAUSED) {
            mVideoView.start();
            mHandler.sendEmptyMessageDelayed(SHOW_TIME,1000);
        } else {
            mVideoView.resetUrl();
        }
        updatePausePlay();
    }

    @OnClick(R.id.img_view_preview)
    public void previewPlay() {

        mHandler.removeMessages(HIDE_NAV);
        mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
//        if(mChannelListBeen == null ||  mChannelListBeen.size() == 0)
//            return;
//
//        channel_index --;
//        if (channel_index < 0)
//            channel_index = mChannelListBeen.size() - 1 ;
//
//        switchViewWithChannel(mChannelListBeen.get(channel_index));
        mPresenter.switchChannel(mIntChannelId,SWITCH_TYPE_UP);
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.buffer_hint));

    }

    @OnClick(R.id.img_view_next)
    public void nextPlay() {
        mHandler.removeMessages(HIDE_NAV);
        mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
//        if(mChannelListBeen == null ||  mChannelListBeen.size() == 0)
//            return;
//        channel_index ++;
//        if (channel_index >= mChannelListBeen.size())
//            channel_index = 0;
//        switchViewWithChannel(mChannelListBeen.get(channel_index));
        mPresenter.switchChannel(mIntChannelId,SWITCH_TYPE_DOWN);
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.buffer_hint));

    }

    @OnClick({R.id.layout_button_local_video,R.id.button_local_video})
    public void onClickLocalActivity(){
        StartActivityUtils.startDownloadManagerActivity(this);
//        onBuyPressed();
    }

    @OnClick({R.id.button_me,R.id.layout_button_me})
    public void onClickMeBtn(){
        toggleMediaControlsVisiblity();
        //if (Utils.sUser != null && !StringUtils.isBlank(Utils.sUser.getToken())) {
            //StartActivityUtils.startPersonalCenterActivity(this);
            Intent intent = new Intent(this, PersonalCenterActivity.class);
            this.startActivityForResult(intent,PLAY_SETTING_RESULT_CODE);
       // } else {
           // ToastUtils.show(this,R.string.no_login_tip);
           // StartActivityUtils.startNoLoginActivity(this, LoginEvent.FROM_ME_LOGIN);
       // }

    }

    @OnClick({R.id.layout_button_message,R.id.button_message})
    public void onClickMessage() {
        if(mIsMessageDialogShow) {
            mLayoutMessageView.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_from_left));
            mLayoutMessageView.setVisibility(View.GONE);
            mIsMessageDialogShow = false;
            mButtonMessage.setBackgroundResource(R.drawable.player_btn_show_message_selector);
            mTextViewMessageButton.setText(getResources().getString(R.string.show_message));
        } else {
            mLayoutMessageView.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.in_from_left));
            mLayoutMessageView.setVisibility(View.VISIBLE);
            mIsMessageDialogShow = true;
            mButtonMessage.setBackgroundResource(R.drawable.player_btn_hide_message_selector);
            mTextViewMessageButton.setText(getResources().getString(R.string.hide_message));
        }
    }


    @OnClick({R.id.layout_button_send_message,R.id.button_send_message})
    public void onClickSendMessageBtn(){
        if(Utils.sUser != null && !StringUtils.isBlank(Utils.sUser.getToken())) {
            if (mClient!=null) {
                if (mClient.getLoginStatus()==0)
                    mClient.login(ApplicationModule.DANMU_HOST,ApplicationModule.DANMU_HOST_PORT,String.valueOf(mIntRoomId), Utils.token);
            }
            if (mIsMessageKeyBoardShow) {
                mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
                mEmotionKeyboard.setVisibility(View.GONE);
                mIsMessageKeyBoardShow = false;
            } else {
                toggleMediaControlsVisiblity();
                mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_in));
                mEmotionKeyboard.setVisibility(View.VISIBLE);
                mEditText.requestFocus();
                mIsMessageKeyBoardShow = true;

            }
        } else {
            // jump to login activity
            StartActivityUtils.startLoginActivity(this,null, LoginEvent.FROM_PLAYER);
        }


    }

    private ChannelContact.IChanelPresenter mPresenter;

    private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
    private static final String CONFIG_CLIENT_ID = "AQ3hEG0QvAWPpwHUaK3obzHcnDsFVaZou7RU74ZvCWb7ciqH_2_Gh8CGIaC0vcAumzNgD3Fo_ldxOMTg";
    private static final int REQUEST_CODE_PAYMENT = 1;


    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID);
            // The following are only used in PayPalFuturePaymentActivity.
//            .merchantName("Example Merchant")
//            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
//            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(savedInstanceState != null){
            Utils.token = savedInstanceState.getString("token");
        }
        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);
        isLoadData = false;
        needPermissions = new String[]{ Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
        super.onCreate(savedInstanceState);
        LogUtils.i(TAG,"onCreate");
    }

    @Override
    protected void initVariables() {
        LogUtils.i("lixd", Utils.sessionid);
        LogUtils.i("lixd", token);

        mPlayUrl = mUrl;

        if(getIntent().hasExtra(IntentParams.VIDEO_URL)){
            from_url = true;
            mPlayUrl = getIntent().getStringExtra(IntentParams.VIDEO_URL);
        }
        mCurrentTime = -1; // 初始化播放时间

        mFov = (int)SPUtils.get(this,Definition.KEY_FOV,Definition.FOV_DEFAULT);
        mProjectionMode = (int)SPUtils.get(this,Definition.KEY_PROJECTION,Definition.TYPE_180_3D_Left_Right);
        mNavigationMode = (int)SPUtils.get(this,Definition.KEY_SNVR_NAVIGATION,Definition.SNVR_NAVIGATION_SENSOR);
        mEyesMode = (int)SPUtils.get(this,KEY_SNVR_EYE_MODE,Definition.SNVR_DOUBLE_EYES_MODE);

        cur_gesture_type = GESTURE_TYPE_NO;


        mPresenter = new ChannelPresenter();
//        mPresenter.registerView(this);

        DefaultBusWrapper.getInstance().register(this);

        mClient = new GiftClient();
        mClient.initialize(this, false);

        mMessageList = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this,mMessageList);

        mInputMethodManager =  (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("token", token);
    }


    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_play);
        ButterKnife.bind(this);

        mLayoutControllerTop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mLayoutControllerBottom.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mLayoutControllerRight.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mEmotionKeyboard.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        mVideoView.setVideoPlayerType(ISnailPlayer.PlayerType.PLAYER_TYPE_SNAIL_VR);
        mVideoView.setPlayFov(mFov);
        mVideoView.setNavigationMode(mNavigationMode);

        setPlayProjection(mProjectionMode);
        setEyesMode(mEyesMode);

        mButtonRoomList.setEnabled(false);
        mRelativeLayoutRoomList.setEnabled(false);

        mButtonMessage.setEnabled(false);
        mRelativeLayoutMessage.setEnabled(false);

        mBufferingView.setVisibility(View.GONE);
        mPlayView.setVisibility(View.GONE);

        mVideoView.setOnStatListener(new ISnailPlayerStateChangeNotification() {
            @Override
            public void notify(ISnailPlayer player, ISnailPlayer.State state) {
                Log.i(TAG,"player state is:" + state.getValue() );
                if (mVideoView!=null) {
                    mVideoView.setPlayFov(mFov);
                    mVideoView.setNavigationMode(mNavigationMode);
                }
                setPlayProjection(mProjectionMode);
                if (state == ISnailPlayer.State.PLAYER_STARTED) {
                    mVideoView.start();
                    mBufferingView.setVisibility(View.GONE);
                    if(mTimerTask!=null){
                        mTimerTask.cancel();
                    }
                    mDuration = mVideoView.getDuration();
                    LogUtils.i(TAG, "player duration :" + mDuration);
                    mHandler.sendEmptyMessageDelayed(SHOW_TIME,1000);
                }
                updatePausePlay();
            }
        });

        mVideoView.setOnEventListener(new ISnailPlayerEventNotification() {

            @Override
            public boolean notify(ISnailPlayer mp, EventType what, int extra) {
                if (what == EventType.PLAYER_EVENT_BUFFERING) {
                    Log.i(TAG, "PLAYER_EVENT_BUFFERING");
                    mBufferingView.setVisibility(View.VISIBLE);
                } else if (what == EventType.PLAYER_EVENT_BUFFERED) {
                    Log.i(TAG, "PLAYER_EVENT_BUFFERED");
                    mBufferingView.setVisibility(View.GONE);
                } else if (what == EventType.PLAYER_EVENT_FINISHED) {
                    Log.d(TAG, "PLAYER_EVENT_FINISHED ");
                    mHandler.removeMessages(SHOW_TIME);
                    mBufferingView.setVisibility(View.GONE);
                    if(mTimerTask!=null) {
                        mTimerTask.cancel();
                    }
                }
                return true;
            }
        });

        mVideoView.setOnErrorListener(new ISnailPlayerErrorNotification() {

            @Override

            public void onError(ISnailPlayer mp, ISnailPlayer.ErrorType error, int extra) {
                ToastUtils.show(PlayActivity.this,getResources().getString(R.string.play_fail));
                mBufferingView.setVisibility(View.GONE);
                mPlayView.setVisibility(View.VISIBLE);
                if (mTimerTask!=null) {
                    mTimerTask.cancel();
                }

            }
        });


        mImgViewPause.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                    mImgViewPause.setImageResource(R.drawable.player_btn_play_selector);
                    mPlayView.setVisibility(View.VISIBLE);
                    mHandler.removeMessages(SHOW_TIME);
                } else {
                    mVideoView.start();
                    mImgViewPause.setImageResource(R.drawable.player_btn_pause_selector);
                    mPlayView.setVisibility(View.GONE);
                    mHandler.sendEmptyMessageDelayed(SHOW_TIME,1000);
                }
            }
        });


        mGestureDetector = new GestureDetector(this, new MyGestureListener());
        if(from_url) {
            try {
                //mVideoView.stopPlayback();
                mVideoView.setVideoPath(getIntent().getStringExtra(IntentParams.VIDEO_URL));
                mVideoView.start();
            } catch (Exception e) {
                ToastUtils.show(this, R.string.play_fail);
            }

            mBufferingView.setVisibility(View.VISIBLE);
        }

        LayoutInflater.from(this).inflate(R.layout.emotionkeyborad,null);

        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mRecyclerViewMessageBox.setLayoutManager(manager);
//        mRecyclerViewMessageBox.addItemDecoration(new SimpleDividerItemDecoration(this));
        mRecyclerViewMessageBox.setAdapter(mMessageAdapter);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.i(TAG,"onResume");
        mPresenter.registerView(this);
        if(mVideoView!=null && hasGetAllPermissions) {
            if (mVideoView.getVideoStatus() == ISnailPlayer.State.PLAYER_PAUSED) {
                mVideoView.start();
                mHandler.sendEmptyMessageDelayed(SHOW_TIME,1000);
            }
        }
       //
    }

    @Override
    protected void hasGetAllPermissions() {
        SpeechResult.init(this, true);
        SpeechResult.getInstance().register(this);
        loadData();
    }

    @Override
    protected void onPause() {
        LogUtils.i(TAG,"onPause");
        mPresenter.unregisterView();
        if(mVideoView!=null){
            if(mVideoView.getVideoStatus() == ISnailPlayer.State.PLAYER_PLAYING)
                mVideoView.pause();
        }
        mHandler.removeMessages(SHOW_TIME);
        super.onPause();
    }

    @Override
    protected void onStop() {
        LogUtils.i(TAG,"onStop");
        if(mVideoView!=null) {
            mVideoView.stop();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        LogUtils.i(TAG,"onDestroy");
        if(hasGetAllPermissions)
          SpeechResult.getInstance().unRegister(this);
        DefaultBusWrapper.getInstance().unregister(this);
//        EventBus.getDefault().unregister(this);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
        if(mClient !=null) {
            mClient.logout();
        }
        mHandler.removeMessages(SHOW_TIME);
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                endGesture();
                return true;
        }
        return super.onTouchEvent(event);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_HEADSETHOOK){
            if(hasGetAllPermissions)
             SpeechResult.getInstance().startSpeech();
            LogUtils.d("speech");
            return true;
        }
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            if(mIsMessageKeyBoardShow) {
                mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
                mEmotionKeyboard.setVisibility(View.GONE);
                mIsMessageKeyBoardShow = false;
                return true;
            }
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == PLAY_SETTING_RESULT_CODE) {
            Log.i(TAG,"onActivityResult:resultCode==PLAY_SETTING_RESULT_CODE");
            mProjectionMode = (int)SPUtils.get(this,Definition.KEY_PROJECTION, Definition.TYPE_180_3D_Left_Right);
            mFov = (int)SPUtils.get(this,KEY_FOV,Definition.FOV_DEFAULT);
            mNavigationMode = (int)SPUtils.get(this,KEY_SNVR_NAVIGATION,Definition.SNVR_NAVIGATION_SENSOR);
            if (mVideoView!=null) {
                mVideoView.setPlayFov(mFov);
                mVideoView.setNavigationMode(mNavigationMode);
            }
            setPlayProjection(mProjectionMode);
            Log.i(TAG,"mFov:" + mFov + "mProjectionMode:" + mProjectionMode + "mNavigationMode:" + mNavigationMode);

        } else if(requestCode == REQUEST_UNITY_CODE && resultCode == RESULT_UNITY_CODE){
            mBufferingView.setVisibility(View.VISIBLE);
            if(data != null && data.hasExtra(IntentParams.UNITY_BACK_PARAM)){
                String json = data.getStringExtra(IntentParams.UNITY_BACK_PARAM);
                if (com.snail.readyvr.util.StringUtils.isJson(json)) {
                    ChannelInfoResponBean.DataBean dataBean = JSON.parseObject(json, ChannelInfoResponBean.DataBean.class);
                    if(dataBean != null){
                        LogUtils.d("dataBean-->" + dataBean);
//                        unityBackToNative(dataBean);
                        showChanelInfo(dataBean);
                    }
                   // UnityBack back = (UnityBack) obj;
                   // LogUtils.d(back + "");

                   /* int index = 0;
                    if(mChannelListBeen != null) {
                        for (ChannelListResponBean.DataBean.ListBean channel : mChannelListBeen) {
                            if (channel.getId() == data.getIntExtra(IntentParams.UNITY_BACK_PARAM, 0)) {
                                channel_index = index;
                                mPresenter.registerView(this);
                                mPresenter.loadChanelInfo(channel.getId());
                                break;
                            }
                            index ++;
                        }
                    }*/
                }else {
                   //mVideoView.stopPlayback();
                    mVideoView.setVideoPath(mPlayUrl);
                    mVideoView.start();
                    mBufferingView.setVisibility(View.VISIBLE);
                    if(mTimerTask!=null) {
                        mTimerTask.cancel();
                    }
                    mTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            showNetSpeed();
                        }
                    };
                    new Timer().schedule(mTimerTask, 1000, 1000); // 1s后启动任务，每1s执行一次
                }
            }

        } else if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));
                        /**
                         *  TODO: send 'confirm' (and possibly confirm.getPayment() to your server for verification
                         * or consent completion.
                         * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                         * for more details.
                         *
                         * For sample mobile backend interactions, see
                         * https://github.com/paypal/rest-api-sdk-python/tree/master/samples/mobile_backend
                         */

                        ToastUtils.show(this,"PaymentConfirmation info received from PayPal");

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        TAG,
                        "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }

    @Override
    public void onSpeechPause() {
        if(mVideoView != null)
            mVideoView.pause();
        updatePausePlay();
    }

    @Override
    public void onSpeechPlay() {
        if(!mVideoView.isPlaying()) {
            mVideoView.start();
            mHandler.sendEmptyMessageDelayed(SHOW_TIME,1000);
        }
        updatePausePlay();
    }

    @Override
    public void onSpeechNext() {
        mPresenter.switchChannel(mIntChannelId,SWITCH_TYPE_DOWN);
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.buffer_hint));
    }

    @Override
    public void onSpeechPrevious() {
        mPresenter.switchChannel(mIntChannelId,SWITCH_TYPE_UP);
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.buffer_hint));
    }

    @Override
    public void onSpeechPositive() {
        if(mVideoView!=null) {
            mVideoView.setOriginalAngle();
        }
    }

    @Override
    public void onSpeechDanMu(String result) {

    }

    @Override
    public void onSpeechResult(String result) {
        if(mIsMessageKeyBoardShow)
            mEmotionKeyboard.setEditeText(result);
    }


    class MyGestureListener implements GestureDetector.OnGestureListener {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            if (mIsMessageKeyBoardShow) {
                mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(),0);
                mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
                mEmotionKeyboard.setVisibility(View.GONE);
                mIsMessageKeyBoardShow = false;
            } else {
                toggleMediaControlsVisiblity();
            }
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            Log.i(TAG, "onScroll");

            float nFristX = e1.getX();
            float nFristY = e1.getY();

            // Log.i(TAG, " nFristX:" + nFristX + " nFristY:" + nFristY);

            int video_width = mVideoView.getWidth();
            int video_height = mVideoView.getHeight();
            Log.i(TAG, " video_width:" + video_width);

            float nCurrentX = e2.getRawX();
            float nCurrentY = e2.getRawY();

            int movePosX = (int) Math.abs(distanceX);
            int movePosY = (int) Math.abs(distanceY);

            // Log.i(TAG, "movePosX:" + movePosX + " movePosY:" + movePosY);

            if (mNavigationMode != Definition.SNVR_NAVIGATION_SENSOR) {
                float phi = distanceX * 360 / video_width;
                float theta = distanceY * mFov / video_height;
                mVideoView.setTouchInfo(phi, theta);

            } else {
                getGestureDirection(movePosX, movePosY);

                if (cur_gesture_type == GESTURE_TYPE_VER) {
                    float _percent = (nFristY - nCurrentY) / video_height;

                    if (nFristX > video_width / 2) {
                        Log.i(TAG, "right");
                    } else {
                        Log.i(TAG, "Left");
                    }
                } else if (cur_gesture_type == GESTURE_TYPE_HRO) {
                    Log.i(TAG, "横向移动");
                }

            }

            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            // TODO Auto-generated method stub
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLongPress(MotionEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2,
                               float velocityX, float velocityY) {
            return false;
        }
    }

    private void endGesture() {
        cur_gesture_type = GESTURE_TYPE_NO;
    }

    private void getGestureDirection(float nX, float nY) {

        if (cur_gesture_type == GESTURE_TYPE_NO) {
            if (nX == 0) {
                if (nY > 15) {
                    cur_gesture_type = GESTURE_TYPE_VER;
                }
            } else if (nY == 0) {
                if (nX > 5) {
                    cur_gesture_type = GESTURE_TYPE_HRO;
                }
            } else {
                if (nX / nY > 3) {
                    cur_gesture_type = GESTURE_TYPE_HRO;
                } else if (nY / nX > 3) {
                    cur_gesture_type = GESTURE_TYPE_VER;
                }
            }
        }
    }


    private void toggleMediaControlsVisiblity() {
        if (mLayoutControllerBottom.getVisibility() == View.VISIBLE) {
            mLayoutControllerTop.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_top_out));
            mLayoutControllerTop.setVisibility(View.GONE);
            mLayoutControllerBottom.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
            mLayoutControllerBottom.setVisibility(View.GONE);
            mLayoutControllerRight.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.out_from_right));
            mLayoutControllerRight.setVisibility(View.GONE);
        } else {
            mLayoutControllerTop.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_top_in));
            mLayoutControllerTop.setVisibility(View.VISIBLE);
            mLayoutControllerBottom.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_in));
            mLayoutControllerBottom.setVisibility(View.VISIBLE);
            mLayoutControllerRight.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),R.anim.in_from_right));
            mLayoutControllerRight.setVisibility(View.VISIBLE);
            updatePausePlay();
            mHandler.removeMessages(HIDE_NAV);
            mHandler.sendEmptyMessageDelayed(HIDE_NAV,5000);
        }
    }

    private static String generateTime(int totalSeconds) {
//        int totalSeconds = (int) (position / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }

    private void updatePausePlay() {
        if (mVideoView.getVideoStatus()!= ISnailPlayer.State.PLAYER_PAUSED) {
            mImgViewPause.setImageResource(R.drawable.player_btn_pause_selector);
            mPlayView.setVisibility(View.GONE);
        } else {
            mImgViewPause.setImageResource(R.drawable.player_btn_play_selector);
            mPlayView.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void loadData() {
        if (Utils.sConnectivityStatus == ConnectivityStatus.OFFLINE){
            mImgNoNetWork.setVisibility(View.VISIBLE);
            mIsOffLine = true;
            return;
        }
        if (StringUtils.isBlank(Utils.sessionid)) {
            GetSessionUtils.getSession(((MyApplication)getApplication()).
                    getApplicationComponent().
                    getRestClient(), GetSessionEvent.FROM_PLAYING);
        } else {
            mPresenter.loadDefaultChannelInfo();
        }
        mBufferingView.setVisibility(View.VISIBLE);

    }


    @Override
    public void showChanelList(ChannelListResponBean chanels) {
     // nothing to do
    }


    @Override
    public void showChanelInfo(ChannelInfoResponBean.DataBean chanelInfo) {
        Log.i("App", "onChangeEvent");

        from_url  = false;

        mButtonRoomList.setEnabled(true);
        mRelativeLayoutRoomList.setEnabled(true);

        mCurChannelBean = chanelInfo;
        mIntChannelId = mCurChannelBean.getId();

        mTxtViewChannelName.setText(mCurChannelBean.getName());
        mRoomInfoBean = mCurChannelBean.getDefault_room_info();
        mTextViewRoomName.setText(mRoomInfoBean.getName());
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.switch_hint) + mRoomInfoBean.getName() + getResources().getString(R.string.wait_hint));
        mChannelOnLineNum.setText(String.valueOf(mRoomInfoBean.getOnline()));
        mIntRoomId = mRoomInfoBean.getId();

        mFov = mRoomInfoBean.getView_angle();
        mDome_H = mRoomInfoBean.getDome_horizontal();
        mDome_V = mRoomInfoBean.getDome_vertical();
        Log.i(TAG,"dome_h:" + mDome_H + "dome_v" + mDome_V);
        mProjectionMode = mRoomInfoBean.getProject_style();
        mNavigationMode = mRoomInfoBean.getControl_model();
        mEyesMode = mRoomInfoBean.getEye_style();

        if (mVideoView!=null) {
            mVideoView.setPlayFov(mFov);
            mVideoView.setNavigationMode(mNavigationMode);
            setEyesMode(mEyesMode);
            setPlayProjection(mProjectionMode);
            if (mDome_H == 0) {
                mDome_H = 180;
            }
            if (mDome_V == 0) {
                mDome_V = 180;
            }
            mVideoView.setVrDomeScreenSize(mDome_H,mDome_V);
        }

        SPUtils.put(this,Definition.KEY_FOV,mFov);
        SPUtils.put(this,Definition.KEY_PROJECTION, mProjectionMode);
        SPUtils.put(this,Definition.KEY_SNVR_NAVIGATION,mNavigationMode);
        SPUtils.put(this,Definition.KEY_SNVR_EYE_MODE,mEyesMode);

        // loading play url
        mPresenter.loadPlayUrl(mIntRoomId);
         // gift client login
        mClient.login(ApplicationModule.DANMU_HOST,ApplicationModule.DANMU_HOST_PORT,String.valueOf(mIntRoomId), Utils.token);
        mMessageList.clear();
        mMessageAdapter.notifyDataSetChanged();
    }

    @Override
    public void showPlayings(PlayUrlResponBean _Bean) {
        mPlayUrl = _Bean.getData().getPlayurl();
        if (StringUtils.isVideoUrl(mPlayUrl)) {
            if(mVideoView!=null) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
                String current_time = df.format(new Date());
                mPlayUrl = mPlayUrl + "?token=" + Utils.token + "&sessionid=" +Utils.sessionid + "&time=" + current_time;
                mVideoView.setVideoPath(mPlayUrl);
                mVideoView.start();
                lastTotalRxBytes = getTotalRxBytes();
                lastTimeStamp = System.currentTimeMillis();
                if(mTimerTask!=null) {
                    mTimerTask.cancel();
                }
                mTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        showNetSpeed();
                    }
                };
                new Timer().schedule(mTimerTask, 1000, 1000); // 1s后启动任务，每1s执行一次
                mBufferingView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void showLoadFailureMsg(int code, String errorMsg) {
        mBufferingView.setVisibility(View.GONE);
        ToastUtils.show(this,errorMsg);
        if (code == 001014) {
            GetSessionUtils.getSession(((MyApplication) getApplication())
                    .getApplicationComponent()
                    .getRestClient(), GetSessionEvent.FROM_PLAYING);
            mBufferingView.setVisibility(View.VISIBLE);
        }
    }


    @Subscribe (thread = EventThread.MAIN_THREAD)
    public void onChannelChangeEvent(ChannelChangeEvent event) {
        Log.i("App", "onChangeEvent");
        if( mIntChannelId == event.mBean.getId())
            return;
        if (mVideoView.getVideoStatus()==ISnailPlayer.State.PLAYER_PLAYING) {
            mVideoView.stopPlayback();
        }
        mIntChannelId = event.mBean.getId();
        mPresenter.loadChanelInfo(mIntChannelId);
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.switch_hint) +event.mBean.getName() + getResources().getString(R.string.wait_hint));
        mButtonRoomList.setEnabled(false);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.NET_WORK_TAG)})
    public void onEventMainThread(ConnectivityChanged event) {
        if (event.getConnectivityStatus() == ConnectivityStatus.OFFLINE) {
            mIsOffLine = true;
            if (mVideoView.isPlaying()) {
                mVideoView.stopPlayback();
            }
            mImgNoNetWork.setVisibility(View.VISIBLE);
        } else {
            if (mIsOffLine) {
                mImgNoNetWork.setVisibility(View.GONE);
                mIsOffLine = false;
                mPresenter.loadChanelList(page_size,page,false,false);
                mBufferingView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(Constant.BusTag.GET_SESSIONID_TAG)})
    public void onSessionEvent(GetSessionEvent event) {
        mBufferingView.setVisibility(View.GONE);
        if (event.getType() == GetSessionEvent.TYPE_SUCCESS) {
            if (event.getFrom() == GetSessionEvent.FROM_PLAYING) {
                mPresenter.loadDefaultChannelInfo();
                mBufferingView.setVisibility(View.VISIBLE);
            }
        } else {
            ToastUtils.show(this,R.string.get_sessionid_error_tip);
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void onRoomChangeEvent(RoomChangeEvent event) {
        mBufferingView.setVisibility(View.VISIBLE);
        mTextViewBuffering.setText(getResources().getString(R.string.switch_hint) +event.mBean.getName() + getResources().getString(R.string.wait_hint));

        from_url = false;
        mRoomInfoBean = event.mBean;
        mTextViewRoomName.setText(mRoomInfoBean.getName());
        mChannelOnLineNum.setText(String.valueOf(mRoomInfoBean.getOnline()));
        mIntRoomId = mRoomInfoBean.getId();

        mFov = mRoomInfoBean.getView_angle();
        mDome_H = mRoomInfoBean.getDome_horizontal();
        mDome_V = mRoomInfoBean.getDome_vertical();
        Log.i(TAG,"dome_h:" + mDome_H + "dome_v" + mDome_V);
        mProjectionMode = mRoomInfoBean.getProject_style();
        mNavigationMode = mRoomInfoBean.getControl_model();
        mEyesMode = mRoomInfoBean.getEye_style();

        if (mVideoView!=null) {
            mVideoView.setPlayFov(mFov);
            mVideoView.setNavigationMode(mNavigationMode);
            setEyesMode(mEyesMode);
            setPlayProjection(mProjectionMode);
            if (mDome_H == 0) {
                mDome_H = 180;
            }
            if (mDome_V == 0) {
                mDome_V = 180;
            }
            mVideoView.setVrDomeScreenSize(mDome_H,mDome_V);
        }

        SPUtils.put(this,Definition.KEY_FOV,mFov);
        SPUtils.put(this,Definition.KEY_PROJECTION, mProjectionMode);
        SPUtils.put(this,Definition.KEY_SNVR_NAVIGATION,mNavigationMode);
        SPUtils.put(this,Definition.KEY_SNVR_EYE_MODE,mEyesMode);

        // loading play url
        mPresenter.loadPlayUrl(mIntRoomId);
        if (mClient.getLoginStatus() != 0) {
            mClient.logout();
        }
        mClient.login(ApplicationModule.DANMU_HOST,ApplicationModule.DANMU_HOST_PORT,String.valueOf(mIntRoomId), token);
        mMessageList.clear();
        mMessageAdapter.notifyDataSetChanged();
    }
    
    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void onMessageEvent(MessageEvent event) {
        Log.i(TAG,"onMessageEvent:" + event.mString);
        if(mIsMessageKeyBoardShow) {
            mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(),0);
            mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
            mEmotionKeyboard.setVisibility(View.GONE);
            mIsMessageKeyBoardShow = false;
        }
        if (event.mIsToAnchor) {
            mClient.sendToAnchorMessage(event.mString,"",null);
        } else {
            mClient.sendMessage(event.mString,"",null);
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD,tags = {@Tag(Definition.BusTag.GIFT_TAG)})
    public void onGiftMessageEvent(GifEvent event) {
        Log.i(TAG,"onGiftMessageEvent:" + event.mString);
        if(mIsMessageKeyBoardShow) {
            mInputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(),0);
            mEmotionKeyboard.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_bottom_out));
            mEmotionKeyboard.setVisibility(View.GONE);
            mIsMessageKeyBoardShow = false;
        }
        mClient.sendGiftMessage(event.mString,"",null);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if(intent.hasExtra(IntentParams.VIDEO_URL)) {
            from_url = true;
            mPlayUrl = intent.getStringExtra(IntentParams.VIDEO_URL);
            try {
               // mVideoView.stopPlayback();
                mVideoView.setVideoPath(mPlayUrl);
                mVideoView.start();
            }catch (Exception e){
                ToastUtils.show(this,R.string.play_fail);
            }

            mBufferingView.setVisibility(View.VISIBLE);
        }
    }

    void initPlayModeFromName(String _name) {
        Pattern p = null;
        Matcher m = null;

        p = Pattern.compile(regEx_180_2D);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_180_2D;
            return;
        }

        p = Pattern.compile(regEx_180_LR);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_180_3D_Left_Right;
            return;
        }

        p = Pattern.compile(regEx_180_TB);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_180_3D_Up_Down;
            return;
        }

        p = Pattern.compile(regEx_360_2D);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_360_2D;
            return;
        }

        p = Pattern.compile(regEx_360_LR);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_360_3D_Left_Right;
            return;
        }

        p = Pattern.compile(regEx_360_TB);
        m = p.matcher(_name);

        if (m.matches()) {
            mProjectionMode = TYPE_360_3D_Up_Down;
            return;
        }

        mProjectionMode = TYPE_360_2D;//SharedPreferencesUtil.getInstance(this).getPlayModel();

    }


    private void setEyesMode(int eyeMode) {
        if(mVideoView == null)
            return;
      /*  if (eyeMode == Definition.SNVR_DOUBLE_EYES_MODE) {
            mButtonSwitch.setBackgroundResource(R.drawable.player_btn_double_eyes_selector);
        } else if (eyeMode == Definition.SNVR_SINGLE_EYES_MODE) {
            mButtonSwitch.setBackgroundResource(R.drawable.player_btn_single_eyes_selector);
        }*/

        mVideoView.setEyesMode(Definition.SNVR_SINGLE_EYES_MODE);

    }

    /**
     * 设置播放模式
     * @param playMode
     */
    private void setPlayProjection(int playMode) {
        if(mVideoView==null)
            return;
        switch (playMode){
            case TYPE_360_3D_Left_Right:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_SBS);
                break;
            case TYPE_360_3D_Up_Down:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_OVU);
                break;
            case TYPE_360_2D:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_2D);
                break;
            case TYPE_180_3D_Left_Right:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_SBS);
                break;
            case TYPE_180_3D_Up_Down:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_OVU);
                break;
            case TYPE_180_2D:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_2D);
                break;
            case TYPE_2D:
                mVideoView.setProjectionType(SNVR_PROJ_PLANE);
                break;
        }
    }

    @Override
    public void onLoginComplete(boolean loginResult) {
        Log.i(TAG,"onLoginComplete");
        if (loginResult) {
            mHandler.sendEmptyMessage(MESSAGE_CLIENT_LOGIN);
        }
    }

    @Override
    public void onDisconnect(int disconnectType) {
        if (disconnectType != 1) {
            mHandler.sendEmptyMessage(RELOGIN_GIFT_SERVER);
        }

    }

    @Override
    public void onSendMessageComplete(boolean sendResult, Object context) {
        Log.i(TAG,"onSendMessageComplete:" + sendResult);
        if (!sendResult) {
            if (mClient.getLoginStatus() == 0) {
                mClient.login(ApplicationModule.DANMU_HOST,ApplicationModule.DANMU_HOST_PORT,String.valueOf(mIntRoomId), Utils.token);
            }
        }

    }

    @Override
    public void onSendGiftMessageComplete(boolean sendResult, Object context) {

    }

    @Override
    public void onReceiveMessage(String message, String reserved,  String uid, String nickName, String icon, int type) {
        Log.i(TAG,"message:" + message + "reserved:" + reserved + "nickName:" + nickName + "icon:" +icon);
        String icon_string = DefEmoticons.StringToEmoji(message);
        Log.i(TAG,"icon_string:" + icon_string);
        SnailMessage _Message = new SnailMessage(icon_string,reserved,nickName,icon);
        mMessageList.add(_Message);
        mHandler.sendEmptyMessage(RECEIVE_NEW_MESSAGE);
    }

    @Override
    public void onReceiveGiftMessage(String giftId, String reserved,  String uid, String nickName, String icon) {
        Log.i(TAG,"message:" + giftId + "reserved:" + reserved + "nickName:" + nickName + "icon:" +icon);
        GiftMessage giftMessage = new GiftMessage(giftId,reserved,nickName,icon);
        Message message = new Message();
        message.what = RECEIVE_NEW_GIFT_MESSAGE;
        message.obj = giftMessage;
        mHandler.sendMessage(message);
    }

    @Override
    public void onUserLogin( String uid, String nickName, int userType, String icon) {

    }

    @Override
    public void onUserLogout( String uid, String nickName) {

    }

    @Override
    public void onUserInfoChanged( String uid, String s, int i, String s1) {

    }


    private void onBuyPressed() {
        /*
         * PAYMENT_INTENT_SALE will cause the payment to complete immediately.
         * Change PAYMENT_INTENT_SALE to
         *   - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
         *   - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
         *     later via calls from your server.
         *
         * Also, to include additional payment details and an item list, see getStuffToBuy() below.
         */
        PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);

        /*
         * See getStuffToBuy(..) for examples of some available payment options.
         */
        Intent intent = new Intent(this, PaymentActivity.class);

        // send the same configuration for restart resiliency
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    private PayPalPayment getThingToBuy(String paymentIntent) {
        return new PayPalPayment(new BigDecimal("0.01"), "USD", "sample item",
                paymentIntent);
    }


}
